import React, { useState, useEffect } from 'react';
import { NavBar, Card, Button, Space, Toast, Modal, Skeleton } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import styles from './CampusCardBound.module.css';

function CampusCardBound() {
  const navigate = useNavigate();
  const [cardInfo, setCardInfo] = useState(null);
  const [transactions, setTransactions] = useState([]);
  const [loading, setLoading] = useState(true);
  const [syncing, setSyncing] = useState(false);

  // 模拟校园卡信息
  const mockCardInfo = {
    campusCard: {
      cardNumber: '2024001001234567',
      balance: 200.00,
      isLost: false
    },
    mealCard: {
      balance: 200.00
    },
    isSynced: true
  };

  // 模拟交易记录
  const mockTransactions = [
    {
      _id: '1',
      type: 'recharge',
      amount: 100.00,
      location: '云缴费充值',
      transactionTime: new Date().toISOString()
    },
    {
      _id: '2',
      type: 'consume',
      amount: -15.50,
      location: '桂园食堂',
      transactionTime: new Date(Date.now() - 86400000).toISOString()
    }
  ];

  // 加载校园卡信息
  const loadCardInfo = async () => {
    try {
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      setCardInfo(mockCardInfo);
      setTransactions(mockTransactions);
    } catch (error) {
      console.error('获取校园卡信息错误:', error);
      Toast.show({ content: '获取信息失败' });
    } finally {
      setLoading(false);
    }
  };

  // 同步余额
  const handleSync = async () => {
    setSyncing(true);
    try {
      // 模拟同步过程
      await new Promise(resolve => setTimeout(resolve, 2000));
      Toast.show({ content: '余额同步成功' });
      await loadCardInfo(); // 重新加载信息
    } catch (error) {
      console.error('同步余额错误:', error);
      Toast.show({ content: '同步失败' });
    } finally {
      setSyncing(false);
    }
  };

  // 解绑校园卡
  const handleUnbind = () => {
    Modal.confirm({
      content: '确定要解绑校园卡吗？解绑后将无法使用校园卡相关功能。',
      onConfirm: async () => {
        try {
          localStorage.removeItem('campusCardBound');
          localStorage.removeItem('campusCardNumber');
          localStorage.removeItem('campusCardBalance');
          Toast.show({ content: '校园卡已解绑' });
          navigate('/campus-card-bind');
        } catch (error) {
          console.error('解绑错误:', error);
          Toast.show({ content: '解绑失败' });
        }
      },
    });
  };

  // 挂失/解挂
  const handleReportLoss = async () => {
    try {
      const newCardInfo = {
        ...cardInfo,
        campusCard: {
          ...cardInfo.campusCard,
          isLost: !cardInfo.campusCard.isLost
        }
      };
      setCardInfo(newCardInfo);
      Toast.show({ 
        content: newCardInfo.campusCard.isLost ? '校园卡已挂失' : '校园卡已解挂' 
      });
    } catch (error) {
      console.error('挂失操作错误:', error);
      Toast.show({ content: '操作失败' });
    }
  };

  useEffect(() => {
    loadCardInfo();
  }, []);

  if (loading) {
    return (
      <div className={styles.container}>
        <NavBar onBack={() => navigate('/layout/home')} className={styles.navBar}>
          我的校园卡
        </NavBar>
        <div className={styles.content}>
          <Skeleton.Title animated />
          <Skeleton.Paragraph lineCount={5} animated />
        </div>
      </div>
    );
  }

  if (!cardInfo) {
    return (
      <div className={styles.container}>
        <NavBar onBack={() => navigate('/layout/home')} className={styles.navBar}>
          我的校园卡
        </NavBar>
        <div className={styles.content}>
          <div className={styles.errorMessage}>
            <p>未找到校园卡信息</p>
            <Button color='primary' onClick={() => navigate('/campus-card-bind')}>
              重新绑定
            </Button>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <NavBar onBack={() => navigate('/layout/home')} className={styles.navBar}>
        我的校园卡
      </NavBar>
      
      <div className={styles.content}>
        {/* 校园卡信息 */}
        <Card className={styles.cardInfo}>
          <div className={styles.cardHeader}>
            <div className={styles.cardIcon}>💳</div>
            <div className={styles.cardDetails}>
              <h3>武汉大学校园卡</h3>
              <p className={styles.cardNumber}>卡号：{cardInfo.campusCard.cardNumber}</p>
              {cardInfo.campusCard.isLost && (
                <p className={styles.lostStatus}>⚠️ 已挂失</p>
              )}
            </div>
          </div>
          <div className={styles.balanceSection}>
            <div className={styles.balanceItem}>
              <span className={styles.balanceLabel}>校园卡余额</span>
              <span className={styles.balanceAmount}>¥{cardInfo.campusCard.balance.toFixed(2)}</span>
            </div>
            {cardInfo.mealCard && (
              <div className={styles.balanceItem}>
                <span className={styles.balanceLabel}>饭卡余额</span>
                <span className={styles.balanceAmount}>¥{cardInfo.mealCard.balance.toFixed(2)}</span>
              </div>
            )}
            <div className={styles.syncStatus}>
              <span className={styles.syncLabel}>
                同步状态：
                {cardInfo.isSynced ? (
                  <span className={styles.synced}>✅ 已同步</span>
                ) : (
                  <span className={styles.notSynced}>⚠️ 未同步</span>
                )}
              </span>
              <Button 
                size='mini' 
                color='primary' 
                onClick={handleSync}
                loading={syncing}
              >
                {syncing ? '同步中...' : '立即同步'}
              </Button>
            </div>
          </div>
        </Card>

        {/* 功能按钮 */}
        <div className={styles.actionButtons}>
          <Space direction='horizontal' wrap>
            <Button 
              color='primary' 
              size='large'
              onClick={() => navigate('/card-recharge')}
            >
              💰 充值
            </Button>
            <Button color='primary' size='large'>
              📊 查询
            </Button>
            <Button 
              color={cardInfo.campusCard.isLost ? 'primary' : 'warning'} 
              size='large' 
              onClick={handleReportLoss}
            >
              {cardInfo.campusCard.isLost ? '🔓 解挂' : '🔒 挂失'}
            </Button>
            <Button color='danger' size='large' onClick={handleUnbind}>
              🔓 解绑
            </Button>
          </Space>
        </div>

        {/* 最近交易记录 */}
        <div className={styles.transactions}>
          <h4 className={styles.sectionTitle}>最近交易</h4>
          {transactions.length > 0 ? (
            transactions.map(transaction => (
              <div key={transaction._id} className={styles.transactionItem}>
                <div className={styles.transactionInfo}>
                  <span className={styles.transactionType}>
                    {transaction.type === 'recharge' ? '充值' : 
                     transaction.type === 'consume' ? '消费' : '同步'}
                  </span>
                  <span className={styles.transactionLocation}>
                    {transaction.location || transaction.description}
                  </span>
                  <span className={styles.transactionTime}>
                    {new Date(transaction.transactionTime).toLocaleString()}
                  </span>
                </div>
                <span className={`${styles.transactionAmount} ${
                  transaction.amount > 0 ? styles.positive : styles.negative
                }`}>
                  {transaction.amount > 0 ? '+' : ''}¥{transaction.amount.toFixed(2)}
                </span>
              </div>
            ))
          ) : (
            <div className={styles.noTransactions}>
              <p>暂无交易记录</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default CampusCardBound;